﻿Imports Sistema_InformacionNaviera.BC
Imports Sistema_InformacionNaviera.BE
Imports Sistema_InformacionNavier.UTIL
Imports System.Drawing 
Imports System.Xml

Public Class DiasLibres

    Inherits PaginaBase
    Dim mCoEntidad, mCoEmbarcador, mDeEntidad, mDeEmbarcador, mTope, mServi, mOk As String
    Dim bGrupo As Boolean
    Dim kAcu As Integer
    Dim dtTipo, dtPuerto, dtPais, dtArea, dtContenedor, dtBL As DataTable

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            sTab.ActiveTabIndex = 0
            CargarCombo("SR", cboServicio)
            CargarCombo("TC", cboTipoCarga)
            CargarCombo("TP", cboTipoPies)
            CargarCombo("PT", cboPuerto)
            CargarCombo("PA", cboPais)
            CargarCombo("AR", cboArea)

            CrearTablas(0)
            CrearTablas(1)
            CrearTablas(2)
            CrearTablas(3)
            CrearTablas(4)
            CrearTablas(5)


            If Session("TipoEvento") = 0 Then
                lblAdmDia.Text = "Nuevo Acuerdo de días libres"
                'Nuevo
                Dim sCodC, sCodE, sDesC, sDesE As String
                sCodC = mCoEntidad : sCodE = mCoEmbarcador : sDesC = mDeEntidad : sDesE = mDeEmbarcador
                txtDiasLibTPies.Text = "" : txtNroAcuerdo.Text = ""

                If Session("Servicio") = Nothing Then
                    cboServicio.SelectedIndex = 0
                Else
                    If Session("Servicio") = "" Then
                        cboServicio.SelectedIndex = 0
                    Else
                        cboServicio.SelectedValue = Session("Servicio").ToString
                    End If
                End If

                txtIniVig.Text = "" : txtFinVig.Text = ""
                dtgPuerto.DataSource = Nothing : dtgPais.DataSource = Nothing : dtgTipoPies.DataSource = Nothing
                dtgBL.DataSource = Nothing : dtgArea.DataSource = Nothing : dtgContenedores.DataSource = Nothing
                dtContenedor = New DataTable : dtPuerto = New DataTable : dtPais = New DataTable : dtArea = New DataTable
                dtBL = New DataTable : dtTipo = New DataTable

            Else
                lblAdmDia.Text = "Modificar Acuerdo de días libres"
                'txtCodCli.Text = Session("CodigoDL")
                spDiaLibreEdicion()
                'txtCodCli.Enabled = False : txtNroDoc.Enabled = False : cboTipoDoc.Enabled = False
            End If
        End If
        If My.Request.Params("__EVENTTARGET") = "MiFuncionPaquetes" Then

            If Session("TipoEvento") = 0 Then
                If Session("BSSCodigoEntidadCON") = Nothing Then
                    txtCodCsne.Text = String.Empty
                Else
                    txtCodCsne.Text = Session("BSSCodigoEntidadCON")
                    txtCsne.Text = Session("BSSNombreEntidadCON")
                End If

                If Session("BSSCodigoEntidadEMB") = Nothing Then
                    txtCodEmb.Text = String.Empty
                Else
                    txtCodEmb.Text = Session("BSSCodigoEntidadEMB")
                    txtEmb.Text = Session("BSSNombreEntidadEMB")
                End If 
            End If
            If Session("BPCodViaje") = Nothing Then
                lblKvje.Text = String.Empty
                txtViaje.Text = String.Empty
            Else
                lblKvje.Text = Session("BPCodViaje")
                txtViaje.Text = Session("BPDesViaje")
            End If
        End If

        If My.Request.Params("__EVENTTARGET") = "MiFuncionPaquetes1" Then

            If Session("BPCodViaje") = Nothing Then
                lblKvje0.Text = Session("BPCodViaje")
                txtViaje1.Text = String.Empty
            Else
                lblKvje0.Text = Session("BPCodViaje")
                txtViaje1.Text = Session("BPDesViaje")
            End If
        End If
    End Sub

    Sub spDiaLibreEdicion()
        Dim objDLibresBE As DiasLibresBE = New DiasLibresBE
        Dim objDLibBE As DiasLibresBE = New DiasLibresBE
        Dim objDLibBC As DiasLibresBC = New DiasLibresBC()


        objDLibBE.Kdli = Session("CodigoDL")
        objDLibresBE = objDLibBC.ListaDiasLibEdicion(objDLibBE)
        If Not objDLibresBE Is Nothing Then
            optCli.Checked = True
            If objDLibresBE.CodCli.Trim <> "" Then
                chkCliente.Checked = True
                txtCodCsne.Text = objDLibresBE.CodCli : txtCsne.Text = objDLibresBE.DesCli
                txtCodCsne.Enabled = False = True : txtCsne.Enabled = False : chkCliente.Enabled = False
            End If

            If objDLibresBE.CodEmb.Trim <> "" Then
                chkEmbarcador.Checked = True
                txtCodEmb.Text = objDLibresBE.CodEmb : txtEmb.Text = objDLibresBE.DesEmb
                txtCodEmb.Enabled = False : txtEmb.Enabled = False : chkEmbarcador.Enabled = False
            End If
            cboServicio.SelectedValue = objDLibresBE.Serv : cboServicio.Enabled = False
            txtNroAcuerdo.Text = objDLibresBE.NAcuerdo : txtNroAcuerdo.Enabled = False
            txtIniVig.Text = objDLibresBE.IniVig : txtFinVig.Text = objDLibresBE.FinVig
            spDetalleDiaLibre()
        End If
    End Sub

    Sub spDetalleDiaLibre()
        Dim objDLibresBE As List(Of DiasLibresDetalleBE) = New List(Of DiasLibresDetalleBE)
        Dim dt As New DataTable
        Dim objDLibBE As DiasLibresDetalleBE = New DiasLibresDetalleBE
        Dim objDLibBC As DiasLibresDetalleBC = New DiasLibresDetalleBC()
        objDLibBE.KdliDet = Session("CodigoDL")
        objDLibBE.Tipo = "CT"
        dt = objDLibBC.ListaDiasLibresDetalle(objDLibBE)

        If dt.Rows.Count > 0 Then
            dtgContenedores.DataSource = dt
            dtgContenedores.DataBind()
            Session("tbTempDiasLibCntr") = dt
        End If

        dt = Nothing
        objDLibBE.Tipo = "BL"
        dt = objDLibBC.ListaDiasLibresDetalle(objDLibBE)
        If dt.Rows.Count > 0 Then
            dtgBL.DataSource = dt
            dtgBL.DataBind()
            Session("tbTempDiasLibBl") = dt
        End If

        dt = Nothing
        objDLibBE.Tipo = "TP"
        dt = objDLibBC.ListaDiasLibresDetalle(objDLibBE)
        If dt.Rows.Count > 0 Then
            dtgTipoPies.DataSource = dt
            dtgTipoPies.DataBind()
            Session("tbTempDiasLibTPies") = dt
        End If


        dt = Nothing
        objDLibBE.Tipo = "PT"
        dt = objDLibBC.ListaDiasLibresDetalle(objDLibBE)
        If dt.Rows.Count > 0 Then
            dtgPuerto.DataSource = dt
            dtgPuerto.DataBind()
            Session("tbTempDiasLibPto") = dt
        End If


        dt = Nothing
        objDLibBE.Tipo = "PA"
        dt = objDLibBC.ListaDiasLibresDetalle(objDLibBE)
        If dt.Rows.Count > 0 Then
            dtgPais.DataSource = dt
            dtgPais.DataBind()
            Session("tbTempDiasLibPai") = dt
        End If


        dt = Nothing
        objDLibBE.Tipo = "AR"
        dt = objDLibBC.ListaDiasLibresDetalle(objDLibBE)
        If dt.Rows.Count > 0 Then
            dtgArea.DataSource = dt
            dtgArea.DataBind()
            Session("tbTempDiasLibAr") = dt
        End If
    End Sub

    Protected Sub btnSalir_Click(sender As Object, e As EventArgs) Handles btnSalir.Click
        Response.Redirect("Consultar_DiasLibres.aspx", True)
    End Sub

    Public Sub CargarCombo(ByVal sTipo As String, cbo As DropDownList)
        Dim listGeneralBE As List(Of GeneralBE) = New List(Of GeneralBE)
        Dim objGeneralBC As GeneralBC = New GeneralBC()

        Dim objUnidadSeleccione As GeneralBE = New GeneralBE
        objUnidadSeleccione.Codigo = 0
        objUnidadSeleccione.Descripcion = "[Seleccione]"
        listGeneralBE.Add(objUnidadSeleccione)
        objUnidadSeleccione.Codigo = sTipo

        listGeneralBE.AddRange(objGeneralBC.ListadoGeneral(objUnidadSeleccione))

        cbo.DataSource = listGeneralBE
        cbo.DataValueField = "Codigo"
        cbo.DataTextField = "Descripcion"
        cbo.DataBind()

    End Sub
     
    Protected Sub btnAgregarCntr_Click(sender As Object, e As EventArgs) Handles btnAgregarCntr.Click

        lblCntrError.Visible = False
        If Val(lblKvje.Text.Trim) > 0 Then
            If txtNroBL.Text.Trim <> "" Then
                If txtPrefCntr.Text.Trim <> "" And txtNroCntr.Text.Trim <> "" Then
                    Dim iCuenta As Integer = 0
                    Dim objDLibresBC As New DiasLibresDetalleBC
                    Dim objDLibresBE As New DiasLibresDetalleBE
                    Dim objDLibresDetBE As New DiasLibresDetalleBE
                    objDLibresBE.Viaje = lblKvje.Text.Trim
                    objDLibresBE.Nave = txtViaje.Text.Trim
                    objDLibresBE.NroBL = txtNroBL.Text.Trim
                    objDLibresBE.NroCtnr = txtPrefCntr.Text.Trim & txtNroCntr.Text.Trim
                    objDLibresDetBE = objDLibresBC.ValidarContenedor(objDLibresBE)
                    If Val(objDLibresDetBE.Kbli.ToString) > 0 And Val(objDLibresDetBE.Viaje.ToString) > 0 Then 

                        Dim drItem As DataRow = Nothing
                        Dim i As Integer = 0
                        Dim dt As DataTable 

                        dt = New DataTable
                        dt = Session("tbTempDiasLibCntr")
            
                    '-------------------------------------------------------------------------------------
                    'agrega datos a tabla temporal 
                    '------------------------------------------------------------------------
                    If dt.Rows.Count > 0 Then
                            If Not ValidaRepetidoVal(dt, 7, txtPrefCntr.Text.Trim & txtNroCntr.Text.Trim, "Dias libres") Then

                                Dim dr As DataRow = dt.NewRow
                                dr("KdliDet") = kAcu
                                dr("CodViaje") = objDLibresDetBE.Viaje
                                dr("Viaje") = txtViaje.Text.Trim
                                dr("Kbli") = objDLibresDetBE.Kbli
                                dr("BLNume") = txtNroBL.Text.Trim
                                dr("PrefCtnr") = txtPrefCntr.Text.Trim
                                dr("NumCtnr") = txtNroCntr.Text.Trim
                                dr("NroCtnr") = txtPrefCntr.Text.Trim & txtNroCntr.Text.Trim

                                dt.Rows.Add(dr)
                                Session("tbTempDiasLibCntr") = dt
                                Me.dtgContenedores.DataSource = SelectDataTable(dt, "", "")
                                Me.dtgContenedores.DataBind()
                                txtViaje.Text = "" : txtNroBL.Text = "" : txtPrefCntr.Text = "" : txtNroCntr.Text = ""
                                Exit Sub
                            Else
                                MsgBox("El contenedor ya está registrado.", MsgBoxStyle.Information, Me.Title)
                                Exit Sub
                            End If

                        Else
                            Dim dr As DataRow = dt.NewRow
                            dr("KdliDet") = kAcu
                            dr("CodViaje") = objDLibresDetBE.Viaje
                            dr("Viaje") = txtViaje.Text.Trim
                            dr("Kbli") = objDLibresDetBE.Kbli
                            dr("BLNume") = txtNroBL.Text.Trim
                            dr("PrefCtnr") = txtPrefCntr.Text.Trim
                            dr("NumCtnr") = txtNroCntr.Text.Trim
                            dr("NroCtnr") = txtPrefCntr.Text.Trim & txtNroCntr.Text.Trim

                            dt.Rows.Add(dr)
                            Session("tbTempDiasLibCntr") = dt
                            Me.dtgContenedores.DataSource = SelectDataTable(dt, "", "")
                            Me.dtgContenedores.DataBind()
                            txtViaje.Text = "" : txtNroBL.Text = "" : txtPrefCntr.Text = "" : txtNroCntr.Text = ""
                        End If
                    Else
                        lblCntrError.Visible = True
                    End If
                End If
            End If
        End If
    End Sub

    Public Sub CrearTablas(iTipo As Integer)
        If iTipo = 0 Then 
            Dim dt As New DataTable
            dt.Columns.Add("KdliDet")
            dt.Columns.Add("CodViaje")
            dt.Columns.Add("Viaje")
            dt.Columns.Add("Kbli")
            dt.Columns.Add("BLNume")
            dt.Columns.Add("PrefCtnr")
            dt.Columns.Add("NumCtnr")
            dt.Columns.Add("NroCtnr")

            Session("tbTempDiasLibCntr") = dt
        ElseIf iTipo = 1 Then
            Dim dt As New DataTable
            dt.Columns.Add("KdliDet")
            dt.Columns.Add("Viaje")
            dt.Columns.Add("Nave")
            dt.Columns.Add("Kbli")
            dt.Columns.Add("NroBL")
            '            dt.Columns.Add("DiasDet")
            Session("tbTempDiasLibBl") = dt
        ElseIf iTipo = 2 Then
            Dim dt As New DataTable
            dt.Columns.Add("KdliDet")
            dt.Columns.Add("TipCar")
            dt.Columns.Add("DesCar")
            dt.Columns.Add("DesTPies")
            dt.Columns.Add("TipCtnr")
            dt.Columns.Add("Pies")
            dt.Columns.Add("CTipo")
            dt.Columns.Add("DiasDet")
            Session("tbTempDiasLibTPies") = dt
        ElseIf iTipo = 3 Then
            Dim dt As New DataTable
            dt.Columns.Add("KdliDet")
            dt.Columns.Add("CodPTo")
            dt.Columns.Add("DesPTo")
            '          dt.Columns.Add("DiasDet")
            Session("tbTempDiasLibPto") = dt
        ElseIf iTipo = 4 Then
            Dim dt As New DataTable
            dt.Columns.Add("KdliDet")
            dt.Columns.Add("CodPais")
            dt.Columns.Add("DesPais")
            '        dt.Columns.Add("DiasDet")
            Session("tbTempDiasLibPai") = dt
        ElseIf iTipo = 5 Then
            Dim dt As New DataTable
            dt.Columns.Add("KdliDet")
            dt.Columns.Add("CodArea")
            dt.Columns.Add("Area")
            '       dt.Columns.Add("DiasDet")
            Session("tbTempDiasLibAr") = dt
        End If

    End Sub

    Function SelectDataTable(ByVal dt As DataTable, ByVal filter As String, ByVal sort As String) As DataTable

        Dim rows As DataRow()
        Dim dtNew As DataTable
        dtNew = dt.Clone()
        rows = dt.Select(filter, sort)
        For Each dr As DataRow In rows
            dtNew.ImportRow(dr)
        Next
        Return dtNew

    End Function

    Function ValidaDetalle(ByVal iTipo As Integer, ByVal sValor As String) As Boolean
        Dim sCod As String = ""
        Dim bValor As Boolean = False
        If iTipo = 1 Then 'validamos que puerto 
            If dtgPais.Rows.Count > 0 Then
                'obtenemos el codigo del pais
                bValor = ValidarDeta("PS", sValor, dtgPais, 2)
                If bValor Then
                    ValidaDetalle = bValor
                    Exit Function
                Else
                    bValor = False
                End If
            End If
            If dtgArea.Rows.Count > 0 Then
                'obtenemos el codigo del área
                bValor = ValidarDeta("PR", sValor, dtgArea, 2, True)
            End If
        ElseIf iTipo = 2 Then 'pais
            If dtgPuerto.Rows.Count > 0 Then
                'obtenemos el codigo del puerto
                bValor = ValidarDeta("SP", sValor, dtgPuerto, 2)
                If bValor Then
                    ValidaDetalle = bValor
                    Exit Function
                Else
                    bValor = False
                End If
            End If
            If dtgArea.Rows.Count > 0 Then
                'obtenemos el codigo del área
                bValor = ValidarDeta("SR", sValor, dtgArea, 2, True)
            End If
        ElseIf iTipo = 3 Then 'area
            If dtgPuerto.Rows.Count > 0 Then
                'obtenemos el codigo del puerto
                bValor = ValidarDeta("RP", sValor, dtgPuerto, 2)
                If bValor Then
                    ValidaDetalle = bValor
                    Exit Function
                Else
                    bValor = False
                End If
            End If
            If dtgPais.Rows.Count > 0 Then
                'obtenemos el codigo del área
                bValor = ValidarDeta("RS", sValor, dtgPais, 2)
            End If

        End If
        Return bValor
    End Function

    Function ValidarDeta(ByVal sTipo As String, ByVal sVal As String, ByVal dtg As GridView, _
                         ByVal iCol As Integer, Optional ByVal bArea As Boolean = False)
        Dim sCod As String = "" : Dim bValor As Boolean = False : Dim dtVal As DataTable = Nothing : Dim i As Integer
        Dim objDLibresBC As New DiasLibresDetalleBC
        Dim objDLibresBE As New DiasLibresDetalleBE
        Dim listDLibresDetlBE As List(Of DiasLibresDetalleBE) = New List(Of DiasLibresDetalleBE)
        objDLibresBE.Tipo = sTipo.Trim
        objDLibresBE.CodArea = sVal.Trim
         
        listDLibresDetlBE = objDLibresBC.ObtieneCodigo(objDLibresBE)
         
        If listDLibresDetlBE.Count <= 0 Then
            ValidarDeta = False
            Exit Function
        End If
        For i = 0 To listDLibresDetlBE.Count - 1
            sCod = listDLibresDetlBE.Item(i).CodPTo.ToString
            bValor = ObtieneValor(dtg, sCod, iCol, bArea)
            If bValor Then
                MsgBox("Ya existe un " & IIf(Mid(sTipo, 2, 1) = "S", "país", IIf(Mid(sTipo, 2, 1) = "R", "área", "puerto")) & _
                       " asociado al " & IIf(Mid(sTipo, 1, 1) = "S", "país", IIf(Mid(sTipo, 1, 1) = "R", "área", "puerto")) & " a ingresar.", vbInformation, Me.Title)
                bValor = True
                Exit For
            End If
        Next
        Return bValor
    End Function

    Function ObtieneValor(ByVal dtg As GridView, ByVal sVal As String, ByVal iCol As Integer, Optional ByVal bArea As Boolean = False) As Boolean
        ObtieneValor = False
        If dtg.Rows.Count > 0 Then
            For i = 0 To dtg.Rows.Count - 1 
                If dtg.Rows.Item(i).Cells(iCol).Text.ToString = sVal Then
                    ObtieneValor = True
                    Exit For 
                End If
            Next
        End If
    End Function 

    Protected Sub btnAgregarPto_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAgregarPto.Click
        If cboPuerto.SelectedIndex > 0 Then
           
            If ValidaDetalle(1, cboPuerto.SelectedValue) Then
                Exit Sub
            End If

            Dim drItem As DataRow = Nothing
            Dim i As Integer = 0
            Dim dt As DataTable
            Dim iValidacion As Integer = 0

            dt = New DataTable
            dt = Session("tbTempDiasLibPto")

            '-------------------------------------------------------------------------------------
            'agrega datos a tabla temporal 
            '------------------------------------------------------------------------
            If dt.Rows.Count > 0 Then
                If Not ValidaRepetido(dt, 1, cboPuerto, "Dias libres") Then
                    Dim dr As DataRow = dt.NewRow
                    dr("KdliDet") = kAcu
                    dr("CodPTo") = cboPuerto.SelectedValue
                    dr("DesPTo") = cboPuerto.Text 

                    dt.Rows.Add(dr)
                    Session("tbTempDiasLibPto") = dt
                    Me.dtgPuerto.DataSource = SelectDataTable(dt, "", "")
                    Me.dtgPuerto.DataBind()
                    Exit Sub
                Else
                    MsgBox("El puerto ya está registrado.", vbInformation, Me.Title)
                    Exit Sub
                End If

            Else
                Dim dr As DataRow = dt.NewRow
                dr("KdliDet") = kAcu
                dr("CodPTo") = cboPuerto.SelectedValue
                dr("DesPTo") = cboPuerto.Text 
                dt.Rows.Add(dr)
                Session("tbTempDiasLibPto") = dt
                Me.dtgPuerto.DataSource = SelectDataTable(dt, "", "")
                Me.dtgPuerto.DataBind()
            End If

        End If
        cboPuerto.SelectedIndex = 0
    End Sub

    Private Sub dtgPuerto_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dtgPuerto.RowCommand
        If dtgPuerto.Rows.Count > 0 Then
            Dim sCodigo As String = Convert.ToString(e.CommandArgument)
            Dim sMensaje As String = String.Empty
            Select Case e.CommandName  '.ToLower
                Case "Eliminar"

                    Dim i As Integer = 0
                    Dim rwEliminar As String
                    Dim dt As New DataTable
                    dt = Session("tbTempDiasLibPto")

                    If dt.Rows.Count > 0 Then

                        Do While i < dt.Rows.Count
                            rwEliminar = dt.Rows(i).Item("CodPTo").ToString

                            If rwEliminar = sCodigo Then
                                dtgPuerto.Rows(i).Visible = False
                                dt.Rows.Remove(dt.Rows(i))
                            End If

                            i = i + 1
                        Loop

                    End If

                    dtgPuerto.DataSource = dt
                    dtgPuerto.DataBind()
            End Select
             
        End If
    End Sub 

    Protected Sub btnAgregarPai_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAgregarPai.Click

        If ValidaDetalle(2, cboPais.SelectedValue) Then
            Exit Sub
        End If

        Dim drItem As DataRow = Nothing
        Dim i As Integer = 0
        Dim dt As DataTable
        Dim iValidacion As Integer = 0

        dt = New DataTable
        dt = Session("tbTempDiasLibPai")
        '-------------------------------------------------------------------------------------
        'agrega datos a tabla temporal 
        '------------------------------------------------------------------------
        If dt.Rows.Count > 0 Then

            If Not ValidaRepetido(dt, 1, cboPais, "Dias libres") Then
                Dim dr As DataRow = dt.NewRow
                dr("KdliDet") = kAcu
                dr("CodPais") = cboPais.SelectedValue
                dr("DesPais") = cboPais.Text 
                dt.Rows.Add(dr)
                Session("tbTempDiasLibPai") = dt
                Me.dtgPais.DataSource = SelectDataTable(dt, "", "")
                Me.dtgPais.DataBind()
                Exit Sub
            Else
                MsgBox("El país ya está registrado.", MsgBoxStyle.Information, Me.Title)
                Exit Sub
            End If

        Else
            Dim dr As DataRow = dt.NewRow
            dr("KdliDet") = kAcu
            dr("CodPais") = cboPais.SelectedValue
            dr("DesPais") = cboPais.Text 
            dt.Rows.Add(dr)
            Session("tbTempDiasLibPai") = dt
            Me.dtgPais.DataSource = SelectDataTable(dt, "", "")
            Me.dtgPais.DataBind()
        End If
        cboPais.SelectedIndex = 0
    End Sub

    Public Shared Function ValidaRepetido(ByVal dt As DataTable, ByVal col As Integer, ByVal cbo As DropDownList, ByVal sMsg As String) As Boolean
        Dim i As Integer
        Dim bRepetido As Boolean = False
        If Not dt Is Nothing Then
            If dt.Rows.Count > 0 Then
                For i = 0 To dt.Rows.Count - 1
                    If dt.Rows(i).Item(col).ToString = cbo.SelectedValue Then 
                        bRepetido = True
                        Exit For
                    End If
                Next
            End If
        End If
        Return bRepetido
    End Function

    Public Shared Function ValidaRepetidoVal(ByVal dt As DataTable, ByVal col As Integer, ByVal strVal As String, ByVal sMsg As String) As Boolean
        Dim i As Integer
        Dim bRepetido As Boolean = False
        If Not dt Is Nothing Then
            If dt.Rows.Count > 0 Then
                For i = 0 To dt.Rows.Count - 1
                    If dt.Rows(i).Item(col).ToString = strVal Then
                        'Alerta("El item seleccionado ya está registrado", False, String.Empty)
                        bRepetido = True
                        Exit For
                    End If
                Next
            End If
        End If
        Return bRepetido
    End Function

    Public Shared Function ValidaRepetidoTPies(ByVal dt As DataTable, ByVal col As Integer, ByVal cbo As DropDownList, ByVal sMsg As String, ByVal sTpies As String, ByVal col2 As Integer) As Boolean
        Dim i As Integer
        Dim bRepetido As Boolean = False
        If Not dt Is Nothing Then
            If dt.Rows.Count > 0 Then
                For i = 0 To dt.Rows.Count - 1
                    If dt.Rows(i).Item(col).ToString = cbo.SelectedValue And dt.Rows(i).Item(col2).ToString = sTpies.Trim Then
                        'Alerta("El item seleccionado ya está registrado", False, String.Empty)
                        bRepetido = True
                        Exit For
                    End If
                Next
            End If
        End If
        Return bRepetido
    End Function

    Protected Sub dtgPais_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dtgPais.RowCommand
        If dtgPais.Rows.Count > 0 Then
            Dim sCodigo As String = Convert.ToString(e.CommandArgument)
            Dim sMensaje As String = String.Empty

            Select Case e.CommandName  '.ToLower
                Case "Eliminar"

                    Dim i As Integer = 0
                    Dim rwEliminar As String
                    Dim dt As New DataTable
                    dt = Session("tbTempDiasLibPai")

                    If dt.Rows.Count > 0 Then

                        Do While i < dt.Rows.Count
                            rwEliminar = dt.Rows(i).Item("CodPais").ToString

                            If rwEliminar = sCodigo Then
                                dtgPais.Rows(i).Visible = False
                                dt.Rows.Remove(dt.Rows(i))
                            End If

                            i = i + 1
                        Loop

                    End If

                    dtgPais.DataSource = dt
                    dtgPais.DataBind()
                     
            End Select
        End If
    End Sub

    Protected Sub btnAgregarArea_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAgregarArea.Click
     
        If ValidaDetalle(3, cboArea.SelectedValue) Then
            Exit Sub
        End If
        Dim drItem As DataRow = Nothing
        Dim i As Integer = 0
        Dim dt As DataTable
        Dim iValidacion As Integer = 0

        dt = New DataTable
        dt = Session("tbTempDiasLibAr")

        '-------------------------------------------------------------------------------------
        'agrega datos a tabla temporal 
        '------------------------------------------------------------------------
        If dt.Rows.Count > 0 Then
            If Not ValidaRepetido(dt, 1, cboArea, "Dias libres") Then

                Dim dr As DataRow = dt.NewRow
                dr("KdliDet") = kAcu
                dr("CodArea") = cboArea.SelectedValue
                dr("Area") = cboArea.Text
                'dr("DiasDet") = txtDiasLibTPies.Text
                dt.Rows.Add(dr)
                Session("tbTempDiasLibAr") = dt
                Me.dtgArea.DataSource = SelectDataTable(dt, "", "")
                Me.dtgArea.DataBind()
                Exit Sub
            Else
                MsgBox("El área ya está registrada.", vbInformation, Me.Title)
                Exit Sub
            End If

        Else
            Dim dr As DataRow = dt.NewRow
            dr("KdliDet") = kAcu
            dr("CodArea") = cboArea.SelectedValue
            dr("Area") = cboArea.Text
            'dr("DiasDet") = txtDiasLibTPies.Text
            dt.Rows.Add(dr)
            Session("tbTempDiasLibAr") = dt
            Me.dtgArea.DataSource = SelectDataTable(dt, "", "")
            Me.dtgArea.DataBind()
        End If
        cboArea.SelectedIndex = 0
    End Sub

    Protected Sub dtgArea_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dtgArea.RowCommand
        If dtgArea.Rows.Count > 0 Then
            Dim sCodigo As String = Convert.ToString(e.CommandArgument)
            Dim sMensaje As String = String.Empty

            Select Case e.CommandName  '.ToLower
                Case "Eliminar" 

                    Dim i As Integer = 0
                    Dim rwEliminar As String
                    Dim dt As New DataTable
                    dt = Session("tbTempDiasLibAr")

                    If dt.Rows.Count > 0 Then

                        Do While i < dt.Rows.Count
                            rwEliminar = dt.Rows(i).Item("CodArea").ToString

                            If rwEliminar = sCodigo Then
                                dtgArea.Rows(i).Visible = False
                                dt.Rows.Remove(dt.Rows(i))
                            End If

                            i = i + 1
                        Loop

                    End If

                    dtgArea.DataSource = dt
                    dtgArea.DataBind()
            End Select
        End If
    End Sub

    Protected Sub btnAgregarTpies_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAgregarTpies.Click
        If cboTipoCarga.SelectedIndex < 0 Then 
            MsgBox("Debe seleccionar un tipo de carga.", vbInformation, Me.Title)
            cboTipoCarga.SelectedIndex = 0
            Exit Sub
        End If
        If Not IsNumeric(txtDiasLibTPies.Text) Then 
            MsgBox("Debe registrar un número válido.", vbInformation, Me.Title)
            Exit Sub
        End If
        If CInt(txtDiasLibTPies.Text) <= 0 Then 
            MsgBox("Debe registrar días libres.", vbInformation, Me.Title)
            Exit Sub
        End If

        If CInt(txtDiasLibTPies.Text) > 45 Then
            MsgBox("Solo se puede ingresar como máximo 45 días libres.", vbInformation, Me.Title)
            Exit Sub
        End If
        Dim bRepetido As Boolean = False
        Dim iIndex As Integer = 0
        Dim drItem As DataRow = Nothing
        Dim i As Integer = 0
        Dim dt As DataTable
        Dim iValidacion As Integer = 0

        dt = New DataTable
        dt = Session("tbTempDiasLibTPies")
        bRepetido = ValidaRepetidoTPies(dt, 1, cboTipoCarga, "Dias Libres", cboTipoPies.SelectedValue, 3)
        If Not bRepetido Then

            '-------------------------------------------------------------------------------------
            'agrega datos a tabla temporal 
            '------------------------------------------------------------------------
            If dt.Rows.Count > 0 Then

                Dim dr As DataRow = dt.NewRow
                dr("KdliDet") = kAcu
                dr("TipCar") = cboTipoCarga.SelectedValue.ToString.Trim
                dr("DesCar") = cboTipoCarga.SelectedItem.Text.ToString.Trim
                dr("DesTPies") = cboTipoPies.SelectedValue.ToString.Trim
                dr("TipCtnr") = cboTipoCarga.SelectedValue.ToString.Trim + cboTipoPies.SelectedValue.ToString.Trim
                dr("Pies") = cboTipoPies.SelectedValue.ToString.Trim
                dr("CTipo") = cboTipoCarga.SelectedValue.ToString.Trim
                dr("DiasDet") = txtDiasLibTPies.Text

                dt.Rows.Add(dr)
                Session("tbTempDiasLibTPies") = dt
                Me.dtgTipoPies.DataSource = SelectDataTable(dt, "", "")
                Me.dtgTipoPies.DataBind()
                Exit Sub

            Else
                Dim dr As DataRow = dt.NewRow

                dr("KdliDet") = kAcu
                dr("TipCar") = cboTipoCarga.SelectedValue.ToString.Trim
                dr("DesCar") = cboTipoCarga.SelectedItem.Text.ToString.Trim
                dr("DesTPies") = cboTipoPies.SelectedValue.ToString.Trim
                dr("TipCtnr") = cboTipoCarga.SelectedValue.ToString.Trim + cboTipoPies.SelectedValue.ToString.Trim
                dr("Pies") = cboTipoPies.SelectedValue.ToString.Trim
                dr("CTipo") = cboTipoCarga.SelectedValue.ToString.Trim
                dr("DiasDet") = txtDiasLibTPies.Text
                dt.Rows.Add(dr)
                Session("tbTempDiasLibTPies") = dt
                Me.dtgTipoPies.DataSource = SelectDataTable(dt, "", "")
                Me.dtgTipoPies.DataBind()
            End If
        Else
            MsgBox("El tipo pies ya está registrado.", vbInformation, Me.Title)
        End If
        cboTipoCarga.SelectedIndex = 0
        cboTipoPies.SelectedIndex = 0
        txtDiasLibTPies.Text = 0
    End Sub 

    Public Shared Function spBuscarItem(ByVal dt As DataTable, ByVal iCol As Integer, ByVal iCol1 As Integer, ByVal strBuscar As String, ByVal strBuscar1 As String) As Integer
        Dim i As Integer
        Dim iIndex As Integer = -1
        For i = 0 To dt.Rows.Count - 1
            If dt.Rows(i).Item(iCol).ToString = strBuscar And dt.Rows(i).Item(iCol1).ToString = strBuscar1 Then
                iIndex = i
                Exit For
            End If
        Next i
        Return iIndex
    End Function

    Private Sub dtgTipoPies_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dtgTipoPies.RowCommand
 
        If dtgTipoPies.Rows.Count > 0 Then
            Dim sCodigo As String = Convert.ToString(e.CommandArgument)
            Dim sMensaje As String = String.Empty

            Select Case e.CommandName  '.ToLower
                Case "Eliminar"

                    Dim i As Integer = 0
                    Dim rwEliminar As String
                    Dim dt As New DataTable
                    dt = Session("tbTempDiasLibTPies")

                    If dt.Rows.Count > 0 Then

                        Do While i < dt.Rows.Count
                            rwEliminar = dt.Rows(i).Item("TipCtnr").ToString

                            If rwEliminar = sCodigo Then
                                dtgTipoPies.Rows(i).Visible = False
                                dt.Rows.Remove(dt.Rows(i))
                            End If

                            i = i + 1
                        Loop

                    End If

                    dtgTipoPies.DataSource = dt
                    dtgTipoPies.DataBind()
            End Select
        End If
    End Sub

    Private Sub dtgContenedores_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dtgContenedores.RowCommand
        If dtgContenedores.Rows.Count > 0 Then
            Dim sCodigo As String = Convert.ToString(e.CommandArgument)
            Dim sMensaje As String = String.Empty

            Select Case e.CommandName  '.ToLower
                Case "Eliminar" 

                    Dim i As Integer = 0
                    Dim rwEliminar As String
                    Dim dt As New DataTable
                    dt = Session("tbTempDiasLibCntr")

                    If dt.Rows.Count > 0 Then

                        Do While i < dt.Rows.Count
                            rwEliminar = dt.Rows(i).Item("NroCtnr").ToString

                            If rwEliminar = sCodigo Then
                                dtgContenedores.Rows(i).Visible = False
                                dt.Rows.Remove(dt.Rows(i))
                            End If

                            i = i + 1
                        Loop

                    End If

                    dtgContenedores.DataSource = dt
                    dtgContenedores.DataBind()
            End Select
        End If
    End Sub 

    Protected Sub btnAgregarBL_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAgregarBL.Click
        lblBlError.Visible = False
        If Val(lblKvje0.Text.Trim) > 0 Then
            If txtNroBL1.Text.Trim <> "" Then
                Dim iCuenta As Integer = 0
                Dim objDLibresBC As New DiasLibresDetalleBC
                Dim objDLibresBE As New DiasLibresDetalleBE
                Dim objDLibresDetBE As New DiasLibresDetalleBE
                objDLibresBE.Viaje = lblKvje0.Text.Trim
                objDLibresBE.Nave = txtViaje1.Text.Trim
                objDLibresBE.NroBL = txtNroBL1.Text.Trim
                objDLibresDetBE = objDLibresBC.ValidarBillOfLading(objDLibresBE)
                If Val(objDLibresDetBE.Kbli.ToString) > 0 And Val(objDLibresDetBE.Viaje.ToString) > 0 Then


                    Dim drItem As DataRow = Nothing
                    Dim i As Integer = 0
                    Dim dt As DataTable
                    Dim iValidacion As Integer = 0

                    dt = New DataTable
                    dt = Session("tbTempDiasLibBl")
                    If ValidaRepetidoVal(dt, 4, txtNroBL1.Text.Trim, "Dias libres") Then
                        MsgBox("El Bl ya está registrado.", vbInformation, Me.Title)
                        Exit Sub
                    End If
                    '-------------------------------------------------------------------------------------
                    'agrega datos a tabla temporal 
                    '------------------------------------------------------------------------
                    If dt.Rows.Count > 0 Then

                        If iValidacion = 0 Then
                            Dim dr As DataRow = dt.NewRow
                            dr("KdliDet") = kAcu
                            dr("Viaje") = objDLibresDetBE.Viaje
                            dr("Nave") = txtViaje1.Text.Trim
                            dr("Kbli") = objDLibresDetBE.Kbli
                            dr("NroBL") = txtNroBL1.Text.Trim
                            'dr("DiasDet") = txtDiasLibTPies.Text

                            dt.Rows.Add(dr)
                            Session("tbTempDiasLibBl") = dt
                            Me.dtgBL.DataSource = SelectDataTable(dt, "", "")
                            Me.dtgBL.DataBind()
                            txtViaje1.Text = "" : txtNroBL1.Text = ""
                            Exit Sub
                        End If

                    Else
                        Dim dr As DataRow = dt.NewRow
                        dr("KdliDet") = kAcu
                        dr("Viaje") = objDLibresDetBE.Viaje
                        dr("Nave") = txtViaje1.Text.Trim
                        dr("Kbli") = objDLibresDetBE.Kbli
                        dr("NroBL") = txtNroBL1.Text.Trim
                        'dr("DiasDet") = txtDiasLibTPies.Text

                        dt.Rows.Add(dr)
                        Session("tbTempDiasLibBl") = dt
                        Me.dtgBL.DataSource = SelectDataTable(dt, "", "")
                        Me.dtgBL.DataBind()
                        txtViaje1.Text = "" : txtNroBL1.Text = ""
                    End If


                Else
                    lblBLError.Visible = True
                End If
            End If
        End If
    End Sub
     

    Function ValidaDatos() As Boolean
        Dim bValida As Boolean = False

        If cboServicio.SelectedIndex < 0 Then  
            MsgBox("Debe seleccionar un servicio", vbInformation, Me.Title)
            Return True
            Exit Function
        End If

        If txtCodCsne.Text Is Nothing Then
            txtCodCsne.Text = ""
        End If

        If txtCodEmb.Text Is Nothing Then
            txtCodEmb.Text = ""
        End If

        If txtCodCsne.Text.Trim = "" And txtCodEmb.Text.Trim = "" Then
            MsgBox("Debe seleccionar al menos un cliente", vbInformation, Me.Title)
            Return True
            Exit Function
        End If

        If txtNroAcuerdo.Text.Trim = "" Then
            MsgBox("Debe registrar el Nro. de Acuerdo", vbInformation, Me.Title)
            Return True
            Exit Function
        End If

        'If txtIniVig.Text.Trim <= Date.Now Then
        '      Alerta("La fecha de Vigencia debe ser mayor a la fecha de hoy", False, String.Empty)
        '    Return True
        '    Exit Function
        'End If

        'If txtFinVig.Text.Trim < txtIniVig.Text.Trim Then
        '      Alerta("La fecha de Fin de Vigencia no puede ser menor a la fecha de Inicio de Vigencia", False, String.Empty)
        '    Return True
        '    Exit Function
        'End If
        Return bValida
    End Function 
     
    Protected Sub dtgBL_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dtgBL.RowCommand
        If dtgBL.Rows.Count > 0 Then
            Dim sCodigo As String = Convert.ToString(e.CommandArgument)
            Dim sMensaje As String = String.Empty

            Select Case e.CommandName  '.ToLower
                Case "Eliminar"

                    Dim i As Integer = 0
                    Dim rwEliminar As String
                    Dim dt As New DataTable
                    dt = Session("tbTempDiasLibBl")

                    If dt.Rows.Count > 0 Then

                        Do While i < dt.Rows.Count
                            rwEliminar = dt.Rows(i).Item("Kbli").ToString

                            If rwEliminar = sCodigo Then
                                dtgBL.Rows(i).Visible = False
                                dt.Rows.Remove(dt.Rows(i))
                            End If

                            i = i + 1
                        Loop

                    End If

                    dtgBL.DataSource = dt
                    dtgBL.DataBind()
            End Select
        End If
    End Sub

    Protected Sub btnNuevo_Click(sender As Object, e As EventArgs) Handles btnNuevo.Click
        Dim strRepetido As String = ""
        Dim bError As Boolean = False
        mOk = True
        If ValidaDatos() Then
            mOk = False
            Exit Sub
        End If
        'obtenemos el detalle para validarlo

        Dim dtCntr As New DataTable
        Dim dtBl As New DataTable
        Dim dtTipies As New DataTable
        Dim dtPto As New DataTable
        Dim dtPais As New DataTable
        Dim dtArea As New DataTable
        Dim bExito As Boolean = False

        dtCntr = Session("tbTempDiasLibCntr")
        dtBl = Session("tbTempDiasLibBl")
        dtTipies = Session("tbTempDiasLibTPies")
        dtPto = Session("tbTempDiasLibPto")
        dtPais = Session("tbTempDiasLibPai")
        dtArea = Session("tbTempDiasLibAr")
        'Validamos Acuerdo
        'strRepetido = ExisteAcuerdo(IIf(mTope = "A", 0, kAcu))
        'If strRepetido.Trim <> "" Then
        '     Alerta("El acuerdo " & strRepetido.Trim & " ya tiene el mismo detalle. El proceso no pudo continuar", False, String.Empty)
        '    Exit Sub
        'End If

        '''''' 
        'Grabar acuerdos
        Dim objDLibBC As New DiasLibresBC
        Dim objDLibBe As New DiasLibresBE
        objDLibBe.Serv = cboServicio.SelectedValue.ToUpper.Trim
        objDLibBe.CodCli = txtCodCsne.Text.Trim.ToUpper
        objDLibBe.CodEmb = txtCodEmb.Text.Trim.ToUpper
        objDLibBe.NAcuerdo = txtNroAcuerdo.Text.ToUpper.Trim
        objDLibBe.IniVig = txtIniVig.Text.Trim.ToUpper
        objDLibBe.FinVig = txtFinVig.Text.Trim.ToUpper()
        objDLibBe.Grp = IIf(optCli.Checked, 0, 1)
        objDLibBe.Ucre = Session("idIusuario")
        objDLibBe.AplHijo = IIf(chkApp.Checked, 0, 1)

        If Session("TipoEvento") = 0 Then
            kAcu = objDLibBC.InsertarDiasLibres(objDLibBe)
            If kAcu > 0 Then
                If Session("TipoEvento") = 1 Then
                    objDLibBC.EliminarDiasLibres(objDLibBe, bExito, "")
                End If

                bError = GrabaDetalle(0, kAcu, dtCntr)
                bError = GrabaDetalle(1, kAcu, dtBl)
                bError = GrabaDetalle(2, kAcu, dtTipies)
                bError = GrabaDetalle(3, kAcu, dtPto)
                bError = GrabaDetalle(4, kAcu, dtPais)
                bError = GrabaDetalle(5, kAcu, dtArea)

            ElseIf kAcu = -1 Then
                MsgBox("Ya existe un acuerdo con el mismo número", vbInformation, Me.Title)
                mOk = False
                Exit Sub
            Else
                MsgBox("Hubo problemas con el ingreso de Días Libres. El proceso no puede continuar.", vbInformation, Me.Title)

                mOk = False
                Exit Sub
            End If
        Else

            objDLibBe.Kdli = Session("CodigoDL")
            kAcu = Session("CodigoDL")
            bExito = objDLibBC.ModificarDiasLibres(objDLibBe)
            If bExito Then
                objDLibBe.Tipo = "D"
                objDLibBC.EliminarDiasLibres(objDLibBe, bExito, "")

                bError = GrabaDetalle(0, kAcu, dtCntr)
                bError = GrabaDetalle(1, kAcu, dtBl)
                bError = GrabaDetalle(2, kAcu, dtTipies)
                bError = GrabaDetalle(3, kAcu, dtPto)
                bError = GrabaDetalle(4, kAcu, dtPais)
                bError = GrabaDetalle(5, kAcu, dtArea)

            Else
                MsgBox("Hubo problemas con el ingreso de Días Libres. El proceso no puede continuar.", vbInformation, Me.Title)

                mOk = False
                Exit Sub
            End If
        End If
      

        Response.Redirect("Consultar_DiasLibres.aspx", True)
    End Sub

    Function GrabaDetalle(iTipo As Integer, iKacu As Integer, dt As DataTable) As Boolean
        Dim objDLibDetBC As New DiasLibresDetalleBC
        Dim objDLibDetBe As DiasLibresDetalleBE
        Dim bExito As Boolean = False
        Dim i As Integer

        For i = 0 To dt.Rows.Count - 1
            objDLibDetBe = New DiasLibresDetalleBE
            objDLibDetBe.KdliDet = iKacu
            If iTipo = 0 Then
                objDLibDetBe.Viaje = Val(dt.Rows(i).Item(1).ToString)
                objDLibDetBe.Kbli = Val(dt.Rows(i).Item(3).ToString)
                objDLibDetBe.PrefCtnr = dt.Rows(i).Item(5).ToString
                objDLibDetBe.NumCtnr = dt.Rows(i).Item(6).ToString
            ElseIf iTipo = 1 Then
                objDLibDetBe.Viaje = Val(dt.Rows(i).Item(1).ToString)
                objDLibDetBe.Kbli = Val(dt.Rows(i).Item(3).ToString)
            ElseIf iTipo = 2 Then
                objDLibDetBe.TipCar = dt.Rows(i).Item(1).ToString
                objDLibDetBe.TipCtnr = dt.Rows(i).Item(2).ToString
                objDLibDetBe.DiasDet = dt.Rows(i).Item(7).ToString
            ElseIf iTipo = 3 Then
                objDLibDetBe.CodPTo = dt.Rows(i).Item(1).ToString
            ElseIf iTipo = 4 Then
                objDLibDetBe.CodPais = dt.Rows(i).Item(1).ToString
            ElseIf iTipo = 5 Then
                objDLibDetBe.CodArea = dt.Rows(i).Item(1).ToString
            End If
            objDLibDetBe.Usu = Session("idIusuario")
            bExito = objDLibDetBC.InsertarDiasLibresDet(objDLibDetBe, iTipo)
        Next

        Return True

    End Function

    Protected Sub chkCliente_CheckedChanged(sender As Object, e As EventArgs) Handles chkCliente.CheckedChanged
        txtCodCsne.Enabled = chkCliente.Checked : txtCsne.Enabled = chkCliente.Checked
        MsgBox(chkCliente.Checked)
    End Sub

    Protected Sub chkEmbarcador_CheckedChanged(sender As Object, e As EventArgs) Handles chkEmbarcador.CheckedChanged
        txtCodEmb.Enabled = chkCliente.Checked : txtEmb.Enabled = chkCliente.Checked
    End Sub
End Class